//
//  DLMenuScrollView.m
//  WXTest
//
//  Created by SL on 15/1/4.
//  Copyright (c) 2015年 Sheng Long. All rights reserved.
//

#import "DLMenuScrollView.h"
#import "CommUtls+View.h"
#import "CommUtls+ViewController.h"

typedef UIView* (^SelectView)(id x,NSInteger index,CGRect rect);

@interface DLMenuScrollView()<UIScrollViewDelegate>

/**
 *  显示名称，字符串数组
 */
@property (nonatomic,strong) NSArray *nameArray;

/**
 *  导航高度
 */
@property (nonatomic,assign) CGFloat navHeight;

/**
 *  菜单栏
 */
@property (nonatomic,strong) DLMenuNavView *navView;

/**
 *  内容页
 */
@property (nonatomic,strong) UIScrollView *scrollView;

/**
 *  获取当前页面
 */
@property (nonatomic,copy) SelectView selectViewBlock;

/**
 *  是否刚开始拖动
 */
@property (nonatomic,assign) BOOL startTracking;

/**
 *  不影响外面设置tag值，里面用字典替代
 */
@property (nonatomic,strong) NSMutableDictionary *viewDictionarys;

/**
 *  NO，执行selectIndex的set属性里面方法，YES不执行
 */
@property (nonatomic,assign) BOOL propertyMethod;

@end

@implementation DLMenuScrollView

- (void)dealloc{
#ifdef DEBUG
    NSLog(@"dealloc -- %@",self.class);
#endif
}

- (instancetype)initWithFrame:(CGRect)frame
                    nameArray:(NSArray *)nameArray
                    navHeight:(CGFloat)navHeigh
                  normalIndex:(NSInteger)normalIndex
                  normalColor:(UIColor *)normalColor
                selectedColor:(UIColor *)selectedColor
                         font:(UIFont *)font
                  currentView:(UIView *(^)(id x,NSInteger index,CGRect rect))currentView {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.viewDictionarys = [NSMutableDictionary new];
        
        self.nameArray = nameArray;
        self.navHeight = navHeigh;
        self.selectViewBlock = currentView;
        
        __weak DLMenuScrollView *blockSelf = self;
        DLMenuNavView *navView = [[DLMenuNavView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, navHeigh)
                                                            menuNames:self.nameArray
                                                          normalColor:normalColor
                                                        selectedColor:selectedColor
                                                                 font:font
                                                              showLoc:^(NSInteger index) {
                                                                  [blockSelf.scrollView setContentOffset:CGPointMake(blockSelf.scrollView.frame.size.width * index, 0) animated:NO];
                                                                  [blockSelf getShowPage:index];
                                                              }];
        self.navView = navView;
        [self addSubview:navView];
        navView.backgroundColor = [UIColor clearColor];
        
        UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(navView.frame), self.frame.size.width, self.frame.size.height-CGRectGetMaxY(navView.frame))];
        self.scrollView = scrollView;
        [scrollView setBounces:NO];
        scrollView.scrollsToTop = NO;
        [scrollView setContentSize:CGSizeMake(frame.size.width*self.nameArray.count, 0)];
        [scrollView setDelegate:self];
        [scrollView setPagingEnabled:YES];
        [scrollView setBackgroundColor:[UIColor clearColor]];
        [scrollView setShowsHorizontalScrollIndicator:NO];
        [self insertSubview:scrollView belowSubview:navView];
        
        _selectIndex = -1;
        self.selectIndex = normalIndex;
    }
    return self;
}

- (void)reloadData:(NSArray *)nameArray selectIndex:(NSInteger)selectIndex {
    self.nameArray = nameArray;
    [self.viewDictionarys removeAllObjects];
    [self.scrollView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width*self.nameArray.count, 0);
    [self.navView reloadData:nameArray];
    
    self.propertyMethod = YES;
    self.selectIndex = selectIndex;
    [self.navView setSelected:_selectIndex animated:NO];
}

/**
 *  设置选中位置
 */
- (void)setSelectIndex:(NSInteger)selectIndex {
    if (_selectIndex != selectIndex) {
        self.currentIndex = selectIndex;
    }
    _selectIndex = selectIndex;
    if (!self.propertyMethod) {
        [self.navView setSelected:_selectIndex animated:!self.startTracking];
    }
    self.propertyMethod = NO;
}

/**
 *  选中内容获取选中页面
 */
- (void)getShowPage:(NSInteger)index {
    self.propertyMethod = YES;
    self.selectIndex = index;
    if (self.selectViewBlock) {
        NSString *tag = [NSString stringWithFormat:@"%ld",(long)index];
        UIView *view = self.viewDictionarys[tag];
        if (!view) {
            view = self.selectViewBlock(self.nameArray[index],index,CGRectMake(self.scrollView.frame.size.width*index, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height));
            [self.scrollView addSubview:view];
            self.viewDictionarys[tag] = view;
        }
        [CommUtls findView:self belongView:view];
    }
    [self setGestureRecognizerEnabled:index];
}

/**
 *  获取菜单栏，子类可重写
 */
- (DLMenuNavView *)fetchNavView {
    DLMenuNavView *navView = [[DLMenuNavView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.navHeight>0?self.navHeight:40)];
    return navView;
}

- (UIView *)fetchCurrentChildView {
    NSInteger index = self.scrollView.contentOffset.x/self.scrollView.frame.size.width;
    NSString *tag = [NSString stringWithFormat:@"%ld",(long)index];
    UIView *view = self.viewDictionarys[tag];
    return view;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (!self.startTracking) {
        self.startTracking = YES;
        NSInteger index = scrollView.contentOffset.x/scrollView.frame.size.width;
        self.selectIndex = index;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.startTracking) {
        [self.navView moveLoc:scrollView.bounds.size.width movingLoc:scrollView.contentOffset.x];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (self.startTracking) {
        NSInteger index = scrollView.contentOffset.x/scrollView.frame.size.width;
        self.selectIndex = index;
    }
    if (!scrollView.tracking) {
        self.startTracking = NO;
    }
}

#pragma mark - IOS7手势控制
/**
 *  设置手势
 *
 *  @param index 第一页支持手势
 */
- (void)setGestureRecognizerEnabled:(NSInteger)index {
    UIViewController *vc = [CommUtls findViewController:self];
    if ([vc isKindOfClass:[UIViewController class]] && vc.navigationController) {
        //设置当前页面IOS7下的手势操作
        vc.navigationController.interactivePopGestureRecognizer.enabled = (index==0);
    }
}

@end
